var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var app = getApp();
Page({
  data: {
    uid:0,
    tuid: 0,
    token: '',
    minHeight:0,
    messages:[],
    messageVal:""
  },
  onLoad: function(data){
    var that = this;
    var navtitle;
    app.GetUserInfo(data.tuid, function(res){
        //设置导航标题
        navtitle = "与" + res.nickname + '的私信';
        wx.setNavigationBarTitle({
            title: navtitle
        });      
    });
    app.LoginUserInfo(function (res) {
      if (res && res != -1) {
      that.setData({
        token: res.token
      });
      }
    });
    this.setData({
      uid:data.uid,
      tuid:data.tuid
    });
    this.getMessages();

    wx.getSystemInfo({
      success: function(res) {
        that.setData({
          minHeight:res.windowHeight-61
        });
      }
    })
  },
  getMessages: function(){
    var that = this;
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "messagecontent",
        "uid": this.data.uid,
        "tuid": this.data.tuid
      },
      success: function(responseData){
        var message = responseData.data;
        if (!responseData.data.msg) {
          for (var i = 0; i < message.length; i++) {
            var time = new Date(message[i].dateline * 1000);
            message[i].formatTime = time.getFullYear() + "-" +
              ((((time.getMonth() + 1) + "").length == 1) ? ("0" + (time.getMonth() + 1)) : time.getMonth())+"-"+
              ((((time.getDate() + 1) + "").length == 1) ? ("0" + (time.getDate() + 1)) : time.getDate());
          }
          that.setData({
            messages: message
          });
        }
      }
    });
  },
  setMessage: function(e){
    this.setData({
      messageVal: e.detail.value
    })
  },
  sendMessage: function(){
    var that = this;
    var token = this.data.token;
    var privatekey = utilMd5.hexMD5(this.data.uid + 'postmessage' + token);
    if(!this.data.messageVal)
      return false;
    util.api({
      method: "POST",
      data: {
          publickey: util.publiccode,
          ac: "postmessage",
          message: this.data.messageVal,
          uid: this.data.uid,
          tuid: this.data.tuid,
          privatekey: privatekey
      },
      success: function (responseData) {
        var data = responseData.data;
        var mes = that.data.messages;
        if (data.msg) {
          var time = new Date(data.dateline * 1000);
          data.formatTime = time.getFullYear() + "-" +
            ((((time.getMonth() + 1) + "").length == 1) ? ("0" + (time.getMonth() + 1)) : time.getMonth()) + "-" +
            ((((time.getDate() + 1) + "").length == 1) ? ("0" + (time.getDate() + 1)) : time.getDate());
          that.setData({
            messages: mes.concat([data])
          });
        }
      }
    });
  }
})